package com.pmt.feedplayer.ui

import androidx.activity.compose.BackHandler
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Pause
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.FastForward
import androidx.compose.material.icons.filled.FastRewind
import androidx.compose.material.icons.filled.SkipNext
import androidx.compose.material.icons.filled.SkipPrevious
import androidx.compose.material3.Text
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import com.google.android.exoplayer2.ExoPlayer
import com.google.android.exoplayer2.MediaItem
import com.pmt.feedplayer.data.LocalVideoScanner
import com.pmt.feedplayer.data.VideoListState
import com.google.android.exoplayer2.ui.AspectRatioFrameLayout
import com.google.android.exoplayer2.ui.PlayerView
import com.pmt.feedplayer.controller.TranslationController
import com.pmt.feedplayer.core.AndroidAudioExtractor
import com.pmt.feedplayer.core.AndroidSpeechRecognizer
import com.pmt.feedplayer.core.AndroidSubtitleManager
import com.pmt.feedplayer.core.AndroidTranslator
import com.pmt.feedplayer.data.VideoItem
import com.pmt.feedplayer.di.DependencyContainer
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import android.view.ViewGroup
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.os.Build
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsControllerCompat

/**
 * Android平台的视频播放页面实现
 */
@Composable
actual fun VideoPlayerScreen(
    videoItem: VideoItem,
    onBack: () -> Unit
) {
    // 获取上下文和协程作用域
    val context = LocalContext.current
    val lifecycleOwner = LocalLifecycleOwner.current
    val coroutineScope = rememberCoroutineScope()
    
    // 创建ViewModel实例 - 为了实现上一个/下一个视频功能
    val viewModel = remember {
        val scanner = LocalVideoScanner()
        scanner.setContext(context)
        VideoListViewModel(scanner)
    }
    
    // 确保ViewModel已经加载了视频列表
    LaunchedEffect(Unit) {
        // 尝试加载一些视频
        viewModel.loadLocalVideos(20)
    }
    
    // 确保当前视频项在ViewModel中被选中
    LaunchedEffect(videoItem) {
        viewModel.selectedVideo.value = videoItem
        // 尝试找到视频在列表中的位置
        if (viewModel.videoListState.value is VideoListState.Success) {
            val videos = (viewModel.videoListState.value as VideoListState.Success).data
            val index = videos.indexOfFirst { it.videoUrl == videoItem.videoUrl }
            if (index >= 0) {
                // 直接调用ViewModel的方法来处理视频点击，这样会自动设置当前索引
                viewModel.onVideoClick(videoItem)
            }
        }
    }
    
    // 依赖注入容器和翻译控制器
    val dependencyContainer = remember { DependencyContainer() }
    var translationController: TranslationController? by remember { mutableStateOf(null) }
    
    // 播放器状态管理
    var player by remember { mutableStateOf<ExoPlayer?>(null) }
    var isPlaying by remember { mutableStateOf(true) }
    var controlsVisible by remember { mutableStateOf(false) }
    var controllerTimeoutJob by remember { mutableStateOf<kotlinx.coroutines.Job?>(null) }
    var currentPosition by remember { mutableStateOf(0L) }
    var duration by remember { mutableStateOf(0L) }
    var progressUpdateJob by remember { mutableStateOf<kotlinx.coroutines.Job?>(null) }
    
    // 处理控件显示/隐藏的协程任务
    val scheduleControlsHide = { durationMs: Long ->
        controllerTimeoutJob?.cancel()
        controllerTimeoutJob = coroutineScope.launch {
            delay(durationMs)
            controlsVisible = false
        }
    }
    
    // 显示控件并设置自动隐藏
    val showControls = {
        controlsVisible = true
        scheduleControlsHide(3000) // 3秒后自动隐藏
    }
    
    // 切换播放/暂停状态
    val togglePlayPause = {
        player?.let { exoPlayer ->
            if (exoPlayer.isPlaying) {
                exoPlayer.pause()
            } else {
                exoPlayer.play()
            }
            isPlaying = exoPlayer.isPlaying
        }
        showControls()
    }
    
    // 快进10秒
    val fastForward = {
        player?.let { exoPlayer ->
            val newPosition = exoPlayer.currentPosition + 10000
            exoPlayer.seekTo(if (newPosition > exoPlayer.duration) exoPlayer.duration else newPosition)
            currentPosition = exoPlayer.currentPosition
        }
        showControls()
    }
    
    // 快退10秒
    val fastRewind = {
        player?.let { exoPlayer ->
            val newPosition = exoPlayer.currentPosition - 10000
            exoPlayer.seekTo(if (newPosition < 0) 0 else newPosition)
            currentPosition = exoPlayer.currentPosition
        }
        showControls()
    }
    
    // 下一个视频 - 使用ViewModel获取下一个视频
    val playNext = { 
        // 获取下一个视频并播放
        val nextVideo = viewModel.getNextVideo()
        if (nextVideo != null) {
            // 重新设置视频源
            val mediaItem = MediaItem.fromUri(nextVideo.videoUrl)
            player?.setMediaItem(mediaItem)
            player?.prepare()
            player?.play()
            isPlaying = true
            // 更新当前视频信息
            currentPosition = 0L
            duration = 0L
        }
        showControls()
    }
    
    // 上一个视频 - 使用ViewModel获取上一个视频
    val playPrevious = { 
        // 获取上一个视频并播放
        val previousVideo = viewModel.getPreviousVideo()
        if (previousVideo != null) {
            // 重新设置视频源
            val mediaItem = MediaItem.fromUri(previousVideo.videoUrl)
            player?.setMediaItem(mediaItem)
            player?.prepare()
            player?.play()
            isPlaying = true
            // 更新当前视频信息
            currentPosition = 0L
            duration = 0L
        }
        showControls()
    }
    
    // 格式化时间
    val formatTime = { milliseconds: Long ->
        val totalSeconds = milliseconds / 1000
        val minutes = totalSeconds / 60
        val seconds = totalSeconds % 60
        String.format("%02d:%02d", minutes, seconds)
    }
    
    // 更新进度
    val startProgressUpdates = {
        progressUpdateJob?.cancel()
        progressUpdateJob = coroutineScope.launch(Dispatchers.Main) {
            while (true) {
                player?.let { exoPlayer ->
                    currentPosition = exoPlayer.currentPosition
                    duration = exoPlayer.duration
                }
                delay(500) // 每500ms更新一次
            }
        }
    }
    
    // 停止进度更新
    val stopProgressUpdates = {
        progressUpdateJob?.cancel()
        progressUpdateJob = null
    }
    
    // 跳转到指定进度
    val seekToPosition = { position: Float ->
        player?.let { exoPlayer ->
            val seekPosition = (position * duration).toLong()
            exoPlayer.seekTo(seekPosition)
            currentPosition = seekPosition
        }
    }
    
    // 初始化播放器
    DisposableEffect(Unit) {
        // 进入全屏模式 - 使用现代API
        val currentActivity = context as? androidx.activity.ComponentActivity
        if (currentActivity != null) {
            val window = currentActivity.window
            
            // 设置全屏标志
            WindowCompat.setDecorFitsSystemWindows(window, false)
            
            // 获取WindowInsetsController
            val insetsController = WindowInsetsControllerCompat(window, window.decorView)
            
            // 隐藏状态栏和导航栏，设置为沉浸式
            insetsController.hide(android.view.WindowInsets.Type.statusBars() or android.view.WindowInsets.Type.navigationBars())
            insetsController.systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
            
            // 设置背景色为黑色
            window.statusBarColor = android.graphics.Color.TRANSPARENT
            window.navigationBarColor = android.graphics.Color.TRANSPARENT
        }
        
        // 使用Media3库创建ExoPlayer实例
        val exoPlayer = ExoPlayer.Builder(context).build()
        player = exoPlayer
        
        // 设置媒体源并准备播放
        val mediaItem = MediaItem.fromUri(videoItem.videoUrl)
        exoPlayer.setMediaItem(mediaItem)
        exoPlayer.prepare()
        exoPlayer.playWhenReady = true
        isPlaying = true
        
        // 监听播放状态变化
        val playbackStateListener = object : com.google.android.exoplayer2.Player.Listener {
            override fun onPlaybackStateChanged(state: Int) {
                if (state == com.google.android.exoplayer2.Player.STATE_READY) {
                    isPlaying = exoPlayer.isPlaying
                    // 开始进度更新
                    startProgressUpdates()
                } else if (state == com.google.android.exoplayer2.Player.STATE_IDLE || 
                           state == com.google.android.exoplayer2.Player.STATE_ENDED) {
                    isPlaying = false
                }
            }
        }
        exoPlayer.addListener(playbackStateListener)
        
        try {
            // 初始化翻译服务组件
            val audioExtractor = AndroidAudioExtractor()
            val speechRecognizer = AndroidSpeechRecognizer(context)
            val translator = AndroidTranslator(context)
            val subtitleManager = AndroidSubtitleManager()
            
            // 设置音频缓冲区大小
            audioExtractor.setBufferSize(500) // 500ms缓冲区
            
            // 初始化依赖容器
            dependencyContainer.initializeTranslationServices(
                audioExtractor = audioExtractor,
                speechRecognizer = speechRecognizer,
                translator = translator,
                subtitleManager = subtitleManager
            )
            
            // 获取翻译控制器
            translationController = dependencyContainer.getTranslationController()
            
            // 开始翻译（如果启用且控制器可用）
            translationController?.let { controller ->
                if (controller.isTranslationEnabled.value) {
                    controller.startTranslation(videoItem.videoUrl)
                }
            }
        } catch (e: Exception) {
            // 优雅处理初始化异常，确保视频播放不受影响
            println("初始化翻译服务时发生错误: ${e.message}")
        }
        
        // 监听生命周期事件
        val observer = LifecycleEventObserver { _, event ->
            when (event) {
                Lifecycle.Event.ON_PAUSE -> {
                    exoPlayer.pause()
                }
                Lifecycle.Event.ON_RESUME -> {
                    if (isPlaying) {
                        exoPlayer.play()
                    }
                }
                else -> {}
            }
        }
        
        lifecycleOwner.lifecycle.addObserver(observer)
        
        // 清理资源
        onDispose {
            // 恢复系统UI
            if (currentActivity != null) {
                val window = currentActivity.window
                WindowCompat.setDecorFitsSystemWindows(window, true)
                
                val insetsController = WindowInsetsControllerCompat(window, window.decorView)
                insetsController.show(android.view.WindowInsets.Type.statusBars() or android.view.WindowInsets.Type.navigationBars())
            }
            
            exoPlayer.removeListener(playbackStateListener)
            lifecycleOwner.lifecycle.removeObserver(observer)
            controllerTimeoutJob?.cancel()
            stopProgressUpdates()
            
            coroutineScope.launch(Dispatchers.Main) {
                exoPlayer.release()
            }
            dependencyContainer.release()
            player = null
            translationController = null
        }
    }
    
    // 返回键处理
    BackHandler {
        onBack()
    }
    
    // 显示播放器视图
    if (player != null) {
        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(Color.Black)
                .clickable {
                    if (controlsVisible) {
                        controlsVisible = false
                        controllerTimeoutJob?.cancel()
                    } else {
                        showControls()
                    }
                }
        ) {
            // 全屏播放器视图
            AndroidView(
                factory = {
                    // 创建Media3的PlayerView并设置播放器
                    val playerView = PlayerView(context)
                    playerView.player = player
                    playerView.useController = false // 禁用原生控制器
                    playerView.resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FIT // 保持原始宽高比，不拉伸视频
                    
                    // 设置布局参数确保全屏
                    val params = ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT)
                    playerView.layoutParams = params
                    
                    playerView
                },
                modifier = Modifier.fillMaxSize()
            )
            
            // 自定义控制层
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .alpha(if (controlsVisible) 1f else 0f)
                    .background(Color.Black.copy(alpha = 0.3f))
                    .clickable { showControls() } // 点击控制层也显示控件
            ) {
                // 顶部操作栏 - 只包含标题和关闭按钮
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .align(Alignment.TopCenter)
                        .padding(16.dp)
                        .background(Color.Black.copy(alpha = 0.5f)) // 顶部栏添加半透明背景
                ) {
                    // 视频标题
                    Text(
                        text = videoItem.title ?: "视频播放",
                        color = Color.White,
                        modifier = Modifier
                            .align(Alignment.CenterStart)
                            .padding(end = 8.dp)
                    )
                    
                    // 自定义关闭按钮
                    IconButton(
                        onClick = onBack,
                        modifier = Modifier
                            .align(Alignment.CenterEnd)
                            .background(Color.Black.copy(alpha = 0.8f), CircleShape)
                    ) {
                        Icon(
                            imageVector = Icons.Default.Close,
                            contentDescription = "关闭",
                            tint = Color.White,
                            modifier = Modifier.size(28.dp)
                        )
                    }
                }
                
                // 底部控制栏 - 整合所有控制功能
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .align(Alignment.BottomCenter)
                        .background(Color.Black.copy(alpha = 0.5f)) // 底部栏添加半透明背景
                ) {
                    // 进度条 - 紧贴顶部
                    val progressBarModifier = remember {
                        Modifier
                            .fillMaxWidth()
                            .height(4.dp)
                            .background(Color.White.copy(alpha = 0.3f))
                    }
                    
                    // 创建一个状态来保存进度条的宽度
                    val progressBarWidth = remember { mutableStateOf(0f) }
                    
                    // 计算进度值
                    val progress = if (duration > 0) currentPosition.toFloat() / duration.toFloat() else 0f
                    
                    // 进度条容器
                    Box(
                        modifier = progressBarModifier
                            .onGloballyPositioned { coordinates ->
                                progressBarWidth.value = coordinates.size.width.toFloat()
                            }
                            .pointerInput(Unit) {
                                detectTapGestures(onTap = { offset ->
                                    showControls()
                                    // 获取点击位置并跳转到相应进度
                                    val clickPosition = offset.x
                                    val seekProgress = clickPosition / progressBarWidth.value
                                    seekToPosition(seekProgress)
                                })
                            }
                            .pointerInput(Unit) {
                                detectDragGestures(onDrag = { change, dragAmount ->
                                    change.consume()
                                    showControls()
                                    // 获取拖动位置并跳转到相应进度
                                    val currentPositionX = change.position.x
                                    // 限制在进度条范围内
                                    val clampedPositionX = currentPositionX.coerceIn(0f, progressBarWidth.value)
                                    val seekProgress = clampedPositionX / progressBarWidth.value
                                    seekToPosition(seekProgress)
                                })
                            }
                    ) {
                        // 进度填充部分
                        Box(
                            modifier = Modifier
                                .fillMaxWidth(progress)
                                .height(4.dp)
                                .background(Color.White)
                        ) {}
                        
                        // 进度条指示器 - 使用计算的偏移量
                        Box(
                            modifier = Modifier
                                .absoluteOffset(x = with(LocalDensity.current) {
                                    // 计算偏移量，确保指示器居中在进度位置
                                    val progressPosition = progress * progressBarWidth.value
                                    (progressPosition - 6.dp.toPx()).toDp()
                                })
                                .size(12.dp)
                                .background(Color.White, CircleShape)
                                .pointerInput(Unit) {
                                    detectDragGestures(onDrag = { change, dragAmount ->
                                        change.consume()
                                        showControls()
                                        // 获取拖动位置并跳转到相应进度
                                        val currentPositionX = change.position.x
                                        // 限制在进度条范围内
                                        val clampedPositionX = currentPositionX.coerceIn(0f, progressBarWidth.value)
                                        val seekProgress = clampedPositionX / progressBarWidth.value
                                        seekToPosition(seekProgress)
                                    })
                                }
                        ) {}
                    }
                    
                    // 控制区域 - 包含时间和按钮
                    Column(
                        modifier = Modifier
                            .padding(16.dp)
                    ) {
                        // 控制按钮组 - 所有控制按钮集中在底部
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(bottom = 8.dp),
                            horizontalArrangement = Arrangement.SpaceBetween,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            // 上一个按钮
                            IconButton(
                                onClick = playPrevious,
                                modifier = Modifier
                                    .background(Color.Black.copy(alpha = 0.8f), CircleShape)
                                    .size(56.dp)
                            ) {
                                Icon(
                                    imageVector = Icons.Default.SkipPrevious,
                                    contentDescription = "上一个",
                                    tint = Color.White,
                                    modifier = Modifier.size(32.dp)
                                )
                            }
                            
                            // 快退按钮
                            IconButton(
                                onClick = fastRewind,
                                modifier = Modifier
                                    .background(Color.Black.copy(alpha = 0.8f), CircleShape)
                                    .size(56.dp)
                            ) {
                                Icon(
                                    imageVector = Icons.Default.FastRewind,
                                    contentDescription = "快退",
                                    tint = Color.White,
                                    modifier = Modifier.size(32.dp)
                                )
                            }
                            
                            // 主要播放/暂停按钮 - 增大尺寸使其更醒目
                            IconButton(
                                onClick = togglePlayPause,
                                modifier = Modifier
                                    .background(Color.White.copy(alpha = 0.9f), CircleShape)
                                    .size(72.dp)
                            ) {
                                Icon(
                                    imageVector = if (isPlaying) Icons.Default.Pause else Icons.Default.PlayArrow,
                                    contentDescription = if (isPlaying) "暂停" else "播放",
                                    tint = Color.Black,
                                    modifier = Modifier.size(48.dp)
                                )
                            }
                            
                            // 快进按钮
                            IconButton(
                                onClick = fastForward,
                                modifier = Modifier
                                    .background(Color.Black.copy(alpha = 0.8f), CircleShape)
                                    .size(56.dp)
                            ) {
                                Icon(
                                    imageVector = Icons.Default.FastForward,
                                    contentDescription = "快进",
                                    tint = Color.White,
                                    modifier = Modifier.size(32.dp)
                                )
                            }
                            
                            // 下一个按钮
                            IconButton(
                                onClick = playNext,
                                modifier = Modifier
                                    .background(Color.Black.copy(alpha = 0.8f), CircleShape)
                                    .size(56.dp)
                            ) {
                                Icon(
                                    imageVector = Icons.Default.SkipNext,
                                    contentDescription = "下一个",
                                    tint = Color.White,
                                    modifier = Modifier.size(32.dp)
                                )
                            }
                        }
                        
                        // 时间显示 - 位于按钮下方
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(top = 8.dp)
                        ) {
                            Text(
                                text = formatTime(currentPosition),
                                color = Color.White,
                                modifier = Modifier
                                    .padding(end = 8.dp)
                            )
                            Text(
                                text = "-" + formatTime(duration - currentPosition),
                                color = Color.White,
                                modifier = Modifier
                                    .weight(1f)
                                    .padding(horizontal = 8.dp)
                            )
                            Text(
                                text = formatTime(duration),
                                color = Color.White,
                                modifier = Modifier
                                    .padding(start = 8.dp)
                            )
                        }
                    }
                }
            }
        }
    }
}